package mspbots.autotask.data.core.contracts;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContractServiceUnitsReceiver extends AbstractToolsUtil {

    private final ContractServiceUnitsRepository contractServiceUnitsRepository;

    @RabbitListener(queues = "auto-task.contract-service-units.sync")
    public void syncTask(ResultMsg content) {

        ContractServiceUnit data = ContractServiceUnit.builder()
                .otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .updatedTime(LocalDateTime.parse(content.getEntity().get("startDate").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .createdTime(LocalDateTime.now())
                .entity(content.getEntity())
                .build();

        this.contractServiceUnitsRepository.findByOtherIdAndTenantId(data.getOtherId(), data.getTenantId())
                .map(old -> {
                    data.setId(old.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.contractServiceUnitsRepository::save)
                .blockOptional(Duration.ofSeconds(10));
    }
}
